import { defineStore } from 'pinia'

export const useRouteStore = defineStore('route', {
    state: () => ({
        tabs: [{ title: '仪表盘', path: '/dashboard' }] as { title: string; path: string }[],
    }),

    actions: {
        loadFromLocalStorage() {
            const savedTabs = localStorage.getItem('routeTabs')
            if (savedTabs) {
                try {
                    const parsedTabs = JSON.parse(savedTabs)
                    if (!parsedTabs.find((tab: { path: string }) => tab.path === '/dashboard')) {
                        parsedTabs.unshift({ title: '仪表盘', path: '/dashboard' })
                    }
                    this.tabs = parsedTabs
                } catch (e) {
                    console.error('解析本地缓存失败:', e)
                    this.tabs = [{ title: '仪表盘', path: '/dashboard' }]
                }
            }
            this.saveToLocalStorage()
        },

        saveToLocalStorage() {
            // 防抖保存，减少频繁写入
            if (this._saveTimeout) clearTimeout(this._saveTimeout)
            this._saveTimeout = setTimeout(() => {
                localStorage.setItem('routeTabs', JSON.stringify(this.tabs))
            }, 500)
        },

        addTab(tab: { title: string; path: string }) {
            if (!this.tabs.some(t => t.path === tab.path)) {
                this.tabs.push(tab)
                this.saveToLocalStorage()
            }
        },

        removeTab(path: string) {
            const index = this.tabs.findIndex(tab => tab.path === path)
            if (index !== -1 && path !== '/dashboard') {
                console.log('删除成功')
                this.tabs.splice(index, 1)
                this.saveToLocalStorage()
            }
        },
    }
})